package cn.edu.sjtu.user_management.service;

import cn.edu.sjtu.user_management.exception.model.ServiceException;
import cn.edu.sjtu.user_management.model.RespStatus;
import cn.edu.sjtu.user_management.model.User;
import cn.edu.sjtu.user_management.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    public void signUp(User user) {
        List<User> users = findUser(null, user.getUserId(), null, null);
        if (users.size() != 0) {
            throw new ServiceException(RespStatus.EXIST_ACCOUNT, this.getClass().getName());
        }
        userRepository.save(user);
    }

    public User updateUserRole(String userId, Integer newRole) {
        List<User> users = findUser(null, userId, null, null);
        if (users.size() == 0) {
            throw new ServiceException(RespStatus.NON_ACCOUNT, this.getClass().getName());
        }
        users.get(0).setRole(newRole);
        return userRepository.save(users.get(0));
    }

    public List<User> findUser(String username, String userId, String password, Integer role) {
        User user = User.builder()
                .userId(userId)
                .password(password)
                .username(username)
                .role(role)
                .build();
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("userId", ExampleMatcher.GenericPropertyMatchers.exact())
                .withMatcher("username", ExampleMatcher.GenericPropertyMatchers.exact())
                .withMatcher("password", ExampleMatcher.GenericPropertyMatchers.exact())
                .withMatcher("role", ExampleMatcher.GenericPropertyMatchers.exact());
        Example<User> example = Example.of(user, matcher);
        return userRepository.findAll(example);
    }
}
